package com.or.log;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.or.utils.C;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;


/**
 * Created by O_R on 2016/2/28.
 */
public class LogWirter implements Runnable{

    private String STOP_FLAG = "____stop____";
    private String logdir = null;
    private File f_log = null;
    private FileOutputStream fout = null;
    private BlockingQueue<String> queue;
    private Calendar data = null;

    /**
     * 日志记录格式按天记录文件
     */
    public LogWirter(Context ctx) throws Exception{
        queue = new ArrayBlockingQueue(10);
        data = Calendar.getInstance();
        if(android.os.Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){/*目录是否存在*/
            logdir = Environment.getExternalStorageDirectory().getPath() + "/" + C.APP_DIR + "/" + C.LOG_SUB + "/";
        }else{
            logdir = ctx.getApplicationContext().getFilesDir().getAbsolutePath() + "/" + C.LOG_SUB + "/";
        }
        File dir = new File(logdir);
        if(!dir.exists()){
            if(!dir.mkdirs()) throw new Exception("创建日志目录失败, 将无法写出日志.");
        }
        selectFile();
        new Thread(this).start();
    }

    public void log(String str){
        queue.add(str);
    }

    private void selectFile() throws Exception{
        f_log = new File(assembledLogName(logdir));
        if(!f_log.exists()) {/*新的一天开始了*/
            f_log.createNewFile();
            if(fout != null) {
                fout.flush();
                fout.close();
            }
            fout = new FileOutputStream(f_log);
        }
    }

    private String assembledLogName(String dir){
        int nowday = data.get(Calendar.DAY_OF_YEAR);
        return dir + "/log_" + nowday + ".txt";
    }

    public void exit(){
        queue.add(STOP_FLAG);
    }

    @Override
    public void run() {
        StringBuilder sb = new StringBuilder();/*循环利用*/
        try {
            while(true){
                String log = queue.take();
                selectFile();
                if(STOP_FLAG.equals(log)){
                    break;
                }
                if(fout != null){
                    sb.append(android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss,", System.currentTimeMillis()).toString());
                    sb.append(log);
                    sb.append("\n");
                    fout.write(sb.toString().getBytes());
                    fout.flush();
                }
                sb.delete(0, sb.length());
                Thread.sleep(1);
            }
        } catch (Exception e) {

        }finally {
            try {
                if(fout != null){
                    fout.flush();
                    fout.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
